package com.gitee.wsl.time.schedule

import com.gitee.wsl.ext.base.Compare
import com.gitee.wsl.ext.base.currentTime
import kotlinx.datetime.TimeZone
import kotlin.time.ExperimentalTime
import kotlin.time.Instant

@OptIn(ExperimentalTime::class)
abstract class AbstractTimeScheduler : TimeScheduler {

    /**
     * Compare two `Schedule` objects based on next occurrence.
     *
     *
     * The next occurrences are calculated based on the current time.
     *
     * @param other the `Schedule` to be compared.
     * @return the value `0` if this `Schedule` next occurrence is equal
     * to the argument `Schedule` next occurrence; a value less than
     * `0` if this `Schedule` next occurrence is before the
     * argument `Schedule` next occurrence; and a value greater than
     * `0` if this `Schedule` next occurrence is after the
     * argument `Schedule` next occurrence.
     */
    override fun compareTo(other: TimeScheduler): Int {
        if (other === this) {
            return 0
        }

        val baseInstant: Instant = currentTime
        val nextAnother = other.next(baseInstant, TimeZone.UTC).getOrNull()
        val nextThis = this.next(baseInstant, TimeZone.UTC).getOrNull()

        return Compare.compare(nextThis, nextAnother)
    }


    fun throwCall(error:String?= null): Result<Instant> = Result.failure(ScheduleException(error))


    companion object {
        const val SMALLEST_SCHEDULE_IN_SECONDS: Int = 5
    }
}
